﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Models;
using Infrastructures;
using Newtonsoft.Json;
using System.Net.Mail;

namespace ConcreteService
{
    public class MessageUtil
    {
        public static void SendPhoneMessage(UserValidation validaiton)
        {
            string code = new Random().Next(1000, 10000).ToString();
            string content = SystemConfig.Get(validaiton.ValidType.ToString()).Replace("{0}", code).Replace("{1}", SystemConfig.Get("CAPTCHAPeriodMins"));
            string url = SystemConfig.Get("MessageUrl") + validaiton.AccountValue + "&content=" + HttpUtility.UrlEncode(content) + "&tag=2";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("apikey", SystemConfig.Get("MessageApiKey"));

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                validaiton.ValidStatus = ValidationStatus.Failed;
                LogUtil.Create(validaiton.AccountValue, EventType.SendMsgError, validaiton.AccountType.ToString(), validaiton.ToString() + ex.Message + ex.InnerException.Message);
                return;
            }

            Stream stream = response.GetResponseStream();
            string StrDate = string.Empty;
            string strVal = string.Empty;
            StreamReader Reader = new StreamReader(stream, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strVal += StrDate;
            }

            if (!strVal.Contains(SystemConfig.Get("CAPTCHSuccessMsg")))
            {
                validaiton.ValidStatus = ValidationStatus.Failed;
                LogUtil.Create(validaiton.AccountValue, EventType.SendMsgError, validaiton.AccountType.ToString(), content + strVal);
                return;
            }

            validaiton.ValidNo = code;
            LogUtil.Create(validaiton.AccountValue, EventType.SendMessage, validaiton.AccountType.ToString(), content + strVal);
            //validaiton.ValidNo = "1234";
        }

        public static void SendMailMessage(UserValidation validaiton)
        {
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.163.com";
            client.Port = 25;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("BingoProject@163.com", "bingoproject2016");

            MailAddress fromAddress = new MailAddress("BingoProject@163.com", "宾果高校");
            MailAddress toAddress = new MailAddress("lixiaob83499@163.com", "小李");
            MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
            mailMessage.Subject = "【宾果高校】验证邮件";
            string mailBody = "<span style='color: red'>test</span><a href='http://www.baidu.com'>立即验证</a>";
            mailMessage.Body = mailBody;
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            mailMessage.Priority = MailPriority.Normal;
            try
            {
                client.Send(mailMessage);
                //client.SendAsync(mailMessage, "ojb");
            }
            catch (Exception ex)
            {
                validaiton.ValidStatus = ValidationStatus.Failed;
                LogUtil.Create(validaiton.UserID, EventType.SendMsgError, validaiton.AccountType.ToString(), validaiton.ToString() + ex.Message + ex.InnerException.Message);
            }
        }

        public static void SendMessage(CommonStatus status, int oper, int receiver = 0, ProjectContract contract = null)
        {
            string content = string.Empty;
            string phoneNo = string.Empty;
            int userID = 0;

            ProjectService projectService = ServiceFactory.CreateInstance<ProjectService>();
            UserInfoService service = ServiceFactory.CreateInstance<UserInfoService>();
            UtilService utilService = ServiceFactory.CreateInstance<UtilService>();

            switch (status)
            {
                case CommonStatus.Verified:

                    if (receiver == 0)
                    {
                        LogUtil.Create("0", EventType.SendMsgError, oper.ToString(), "收信人为空");
                        return;
                    }

                    phoneNo = GetPhoneNo(receiver.ToString(), service, oper);
                    content = SystemConfig.Get(status.ToString());

                    break;
                case CommonStatus.Confirmed:
                case CommonStatus.Effective:

                    if (contract == null)
                    {
                        LogUtil.Create("0", EventType.SendMsgError, oper.ToString(), "无合同信息");
                        return;
                    }

                    var project = projectService.Get<Project>(contract.ProjectID.ToString());
                    if (project == null)
                    {
                        LogUtil.Create(contract.ProjectID.ToString(), EventType.SendMsgError, oper.ToString(), "无活动信息");
                        return;
                    }

                    int creatorID = status == CommonStatus.Confirmed ? project.CreatorID : contract.ContractorID;
                    string groupName = status == CommonStatus.Confirmed ? contract.ContractorName : project.CreatorName;

                    var user = service.Get<UserInfo>(creatorID.ToString());
                    if (user == null || user.UserName.IsNullOrEmpty() || user.UserName.Length != 11)
                    {
                        LogUtil.Create(creatorID.ToString(), EventType.SendMsgError, oper.ToString(), "未找到该用户手机号");
                        return;
                    }

                    phoneNo = user.UserName;
                    userID = user.UserNo;

                    content = SystemConfig.Get(user.Role.ToString() + status.ToString()).Replace("{0}", groupName);

                    if (project.CreatorType == APPRole.Student && contract.AgentID != 0 && status == CommonStatus.Effective)
                    {
                        string msg = SystemConfig.Get("Agent" + status.ToString()).Replace("{0}", project.CreatorName).Replace("{1}", contract.ContractorName);

                        var agent = service.Get<UserInfo>(contract.AgentID.ToString());
                        if (agent == null)
                        {
                            LogUtil.Create(contract.AgentID.ToString(), EventType.SendMsgError, oper.ToString(), "未找到该代理管手机号");
                            return;
                        }

                        //Send(agent.UserName, msg, oper);
                        Send(agent.UserName, msg, contract.AgentID, utilService, oper);
                    }

                    break;
                case CommonStatus.FeedbackSubmitted:
                case CommonStatus.FeedbackApproved:
                case CommonStatus.FeedbackRejected:

                    if (contract == null)
                    {
                        LogUtil.Create("0", EventType.SendMsgError, oper.ToString(), "无合同信息");
                        return;
                    }

                    var projectRec = projectService.Get<Project>(contract.ProjectID.ToString());
                    if (projectRec == null)
                    {
                        LogUtil.Create(contract.ProjectID.ToString(), EventType.SendMsgError, oper.ToString(), "无活动信息");
                        return;
                    }

                    int rec = 0;
                    var desc = string.Empty;

                    if (status == CommonStatus.FeedbackSubmitted)
                    {
                        rec = projectRec.CreatorType == APPRole.Student ? contract.ContractorID : projectRec.CreatorID;
                        desc = projectRec.CreatorType == APPRole.Student ? projectRec.CreatorName : contract.ContractorName;
                    }
                    else
                    {
                        rec = projectRec.CreatorType == APPRole.Student ? projectRec.CreatorID : contract.ContractorID;
                        desc = projectRec.CreatorType == APPRole.Student ? contract.ContractorName : projectRec.CreatorName;
                    }

                    var role = status == CommonStatus.FeedbackSubmitted ? APPRole.Student.ToString() : APPRole.Company.ToString();

                    var userRec = service.Get<UserInfo>(rec.ToString());
                    if (userRec == null || userRec.UserName.IsNullOrEmpty() || userRec.UserName.Length != 11)
                    {
                        LogUtil.Create(rec.ToString(), EventType.SendMsgError, oper.ToString(), "未找到该用户手机号");
                        return;
                    }

                    phoneNo = userRec.UserName;
                    userID = userRec.UserNo;
                    content = SystemConfig.Get(role + status.ToString()).Replace("{0}", desc);

                    if (contract.AgentID != 0)
                    {
                        var agent = service.Get<UserInfo>(contract.AgentID.ToString());
                        if (agent == null)
                        {
                            LogUtil.Create(contract.AgentID.ToString(), EventType.SendMsgError, oper.ToString(), "未找到该代理管手机号");
                            return;
                        }

                        //Send(agent.UserName, content, oper);
                        Send(agent.UserName, content, contract.AgentID, utilService, oper);
                    }

                    break;
                default:
                    return;
            }

            if (content.IsNullOrEmpty() || phoneNo.IsNullOrEmpty())
            {
                LogUtil.Create("0", EventType.SendMsgError, oper.ToString(), "手机号码或者内容为空");
                return;
            }

            Send(phoneNo, content, userID, utilService, oper);
        }

        private static void Send(string phoneNo, string content, int userNo, UtilService service, int oper = 0)
        {
            string url = SystemConfig.Get("MessageUrl") + phoneNo + "&content=" + HttpUtility.UrlEncode(content) + "&tag=2";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("apikey", SystemConfig.Get("MessageApiKey"));

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                LogUtil.Create(phoneNo, EventType.SendMsgError, oper.ToString(), content + ex.Message + ex.InnerException.Message);
                return;
            }

            Stream stream = response.GetResponseStream();
            string StrDate = string.Empty;
            string strVal = string.Empty;
            StreamReader Reader = new StreamReader(stream, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strVal += StrDate;
            }

            if (!strVal.Contains(SystemConfig.Get("CAPTCHSuccessMsg")))
            {
                LogUtil.Create(phoneNo, EventType.SendMsgError, oper.ToString(), content + ";" + strVal);
                return;
            }

            LogUtil.Create(phoneNo, EventType.SendMessage, oper.ToString(), content + ";" + url + ";" + strVal);

            UserMessage msg = new UserMessage();
            msg.MessageType = UserMessageType.SystemMessage;
            msg.Sender = oper.ToString();
            msg.Receiver = userNo.ToString();
            msg.Status = CommonStatus.Pending;
            msg.SendType = AccountType.Phone;
            msg.Content = content;

            service.CreateUserMessage(msg, oper.ToString());
        }

        private static string GetPhoneNo(string userNo, UserInfoService service, int oper)
        {
            var user = service.Get<UserInfo>(userNo.ToString());
            if (user == null || user.UserName.IsNullOrEmpty() || user.UserName.Length != 11)
            {
                LogUtil.Create(userNo.ToString(), EventType.SendMsgError, oper.ToString(), "未找到该用户手机号");
                return string.Empty;
            }

            return user.UserName;
        }
    }

    public class MessageInfo
    {
        public string MessageType { get; set; }
        public string From { get; set; }
        public string To { get; set; }
        public IList<string> CC { get; set; }
        public string Subject { get; set; }
        public string Content { get; set; }

    }
}